from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from typing import List, Optional

from app.db.database import get_db
from app.core.security import get_current_user
from app.schemas.post import Post, PostBrief, PostCreate, PostUpdate, Comment, CommentCreate
from app.crud import post as post_crud

router = APIRouter()

@router.get("/", response_model=List[PostBrief])
async def read_posts(
    skip: int = 0,
    limit: int = 100,
    user_id: Optional[int] = None,
    campsite_id: Optional[int] = None,
    db: Session = Depends(get_db)
):
    """获取帖子列表"""
    posts = post_crud.get_posts(
        db, 
        skip=skip, 
        limit=limit, 
        user_id=user_id, 
        campsite_id=campsite_id,
        is_published=True
    )
    return posts

@router.post("/", response_model=Post, status_code=status.HTTP_201_CREATED)
async def create_post(
    post: PostCreate,
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """创建新帖子"""
    return post_crud.create_post(db=db, post=post, user_id=current_user["id"])

@router.get("/{post_id}", response_model=Post)
async def read_post(post_id: int, db: Session = Depends(get_db)):
    """获取指定ID的帖子"""
    db_post = post_crud.get_post(db, post_id=post_id)
    if not db_post:
        raise HTTPException(status_code=404, detail="帖子不存在")
    
    # 增加浏览次数
    post_crud.increment_view_count(db, post_id=post_id)
    
    return db_post

@router.put("/{post_id}", response_model=Post)
async def update_post(
    post_id: int,
    post_update: PostUpdate,
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """更新帖子"""
    updated_post = post_crud.update_post(
        db, 
        post_id=post_id, 
        post_update=post_update,
        user_id=current_user["id"]
    )
    if not updated_post:
        raise HTTPException(status_code=404, detail="帖子不存在或您无权更新")
    return updated_post

@router.delete("/{post_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_post(
    post_id: int,
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """删除帖子"""
    result = post_crud.delete_post(db, post_id=post_id, user_id=current_user["id"])
    if not result:
        raise HTTPException(status_code=404, detail="帖子不存在或您无权删除")
    return {"status": "success"}

@router.post("/{post_id}/like", status_code=status.HTTP_201_CREATED)
async def like_post(
    post_id: int,
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """点赞帖子"""
    like = post_crud.like_post(db, post_id=post_id, user_id=current_user["id"])
    if not like:
        raise HTTPException(status_code=404, detail="帖子不存在")
    return {"status": "success"}

@router.delete("/{post_id}/like", status_code=status.HTTP_204_NO_CONTENT)
async def unlike_post(
    post_id: int,
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """取消点赞帖子"""
    result = post_crud.unlike_post(db, post_id=post_id, user_id=current_user["id"])
    if not result:
        raise HTTPException(status_code=404, detail="未找到点赞记录")
    return {"status": "success"}

@router.post("/{post_id}/comments", response_model=Comment, status_code=status.HTTP_201_CREATED)
async def create_comment(
    post_id: int,
    comment: CommentCreate,
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """创建评论"""
    db_comment = post_crud.create_comment(
        db, 
        post_id=post_id, 
        user_id=current_user["id"], 
        comment=comment
    )
    if not db_comment:
        raise HTTPException(status_code=404, detail="帖子不存在或父评论不存在")
    return db_comment

@router.get("/{post_id}/comments", response_model=List[Comment])
async def read_comments(
    post_id: int,
    skip: int = 0,
    limit: int = 100,
    db: Session = Depends(get_db)
):
    """获取帖子的评论列表"""
    # 验证帖子是否存在
    db_post = post_crud.get_post(db, post_id=post_id)
    if not db_post:
        raise HTTPException(status_code=404, detail="帖子不存在")
    
    comments = post_crud.get_comments(db, post_id=post_id, skip=skip, limit=limit)
    return comments 